<template>
  <a-modal
    destroyOnClose
    :visible="visible"
    :title="title"
    @update:visible="update"
    @ok="ok"
  >
    <Form ref="formRef" v-model:form="form" :formList="formList" :btnConfig="null">
      <template #parent_id>
        <a-tree-select
          v-model:value="form.parent_id"
          :tree-data="menuTree"
          style="width: 100%"
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
          placeholder="请选择上级菜单"
          allow-clear
          :field-names="{
            children: 'children',
            label: 'display_name',
            value: 'id',
          }"
        />
      </template>
    </Form>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, defineProps, toRefs, defineEmits, watch, onMounted } from "vue";
import Form from "@/components/Form";
import { formList } from "./href";
import { menuApi } from "@/api/menu";

const emits = defineEmits(["update:visible", "reload"]);
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  tempData: {
    default: {},
  },
});
const { visible, tempData } = toRefs(props);
const title = ref("提示");
const formRef = ref();
const form = ref({});
const menuTree = ref([]);

watch(visible, (e) => {
  if (!e) return;
  const { id } = tempData.value;
  if (id) title.value = "修改菜单";
  else title.value = "新增菜单";
  form.value = tempData.value;
  getMenuTree();
});

function update(e) {
  emits("update:visible", e);
}
async function ok() {
  await formRef.value.save();
  if (!form.value.parent_id) form.value.parent_id = "0";
  await menuApi.edit(form.value);
  emits("update:visible", false);
  emits("reload");
}

function getMenuTree() {
  menuApi.page().then((res) => {
    menuTree.value = res.list;
  });
}
</script>

<style lang="less" scoped></style>
